import { createStore } from "vuex";

export default createStore({
  state: {
    isAuthenticated: !!localStorage.getItem("token"), // 初始化时从 localStorage 恢复认证状态
    token: localStorage.getItem("token") || null, // 初始化时从 localStorage 恢复 Token
    sharedValue: null, // 共享的状态
  },
  mutations: {
    login(state, payload) {
      // console.log("Updating state in login mutation:", payload);
      state.isAuthenticated = true;
      state.token = payload.token;

      // 将 Token 存储到 localStorage
      localStorage.setItem("token", payload.token);
    },
    logout(state) {
      console.log('logout');
      state.isAuthenticated = false;
      state.token = null;

      // 清除 localStorage 中的 Token
      localStorage.removeItem("token");
    },
    // 自定义 mutation
    setSharedValue(state, value) {
      state.sharedValue = value;
    },
    clearSharedValue(state) {
      state.sharedValue = null; // 清空状态
    },
  },
  actions: {
    login({ commit }, payload) {
      // console.log("Dispatching login action with payload:", payload);
      //触发login mutation
      commit("login", payload);
    },
    logout({ commit }) {
      commit("logout");
    },
    // 自定义 action
    updateSharedValue({ commit }, value) {
      console.log("set");
      commit("setSharedValue", value);
    },
    clearSharedValue({ commit }) {
      console.log("clear");
      commit("clearSharedValue");
    },
  },
});
